package com.epam.utils;

import java.io.Serializable;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;

import org.apache.log4j.Logger;

@ManagedBean(name = "language")
@SessionScoped
public class LanguageBean implements Serializable {

	private static final long serialVersionUID = 1L;

	private static Logger log = Logger.getLogger(LanguageBean.class);
	private String localeCode;

	private static Map<String, Locale> countries;

	private Locale locale = FacesContext.getCurrentInstance().getViewRoot()
			.getLocale();

	static {
		countries = new LinkedHashMap<String, Locale>();
		countries.put("English", new Locale("en"));
		countries.put("Русский", new Locale("ru"));
		// label, value
	}

	public Map<String, Locale> getCountriesInMap() {
		return countries;
	}

	public Locale getLocale() {
		return locale;
	}

	public String getLanguage() {
        return locale.getLanguage();
    }
	
	public String getLocaleCode() {
		return localeCode;
	}

	public void setLocaleCode(String localeCode) {
		this.localeCode = localeCode;
	}

	// value change event listener
	public void countryLocaleCodeChanged(ValueChangeEvent e) {

		String newLocaleValue = e.getNewValue().toString();
		log.debug("lng bean " + newLocaleValue);
		// loop country map to compare the locale code
		for (Entry<String, Locale> entry : countries.entrySet()) {

			if (entry.getValue().toString().equals(newLocaleValue)) {

				FacesContext.getCurrentInstance().getViewRoot()
						.setLocale(entry.getValue());
				log.debug("lng bean " + entry.getValue());
			}
		}
	}

}